<template>
	<view class="wrap">
		<view class="search-bar">
			<view class="search-bar-inp">
				<input v-model.trim="keywords" placeholder="搜索零部件" placeholder-style="color:#ccc" type="text" value=""
					confirm-type="search" @confirm="searchFuc" :focus="focusState" @blur="focusState = false"
					@input="searchFuc" />
				<view class="marginR" v-if="keywords" @click="searchClear">
					<uni-icons size="16" color="#999999" type="clear"></uni-icons>
				</view>
				<view class="btn" @click="searchFuc" v-else>
					<uni-icons size="22" color="#0091ff" type="search"></uni-icons>
				</view>
			</view>
			<view class="line" v-if="showOther"></view>
			<view class="search-bar-inp" v-if="showOther">
				<input v-model="other" placeholder="请输入自定义名称" placeholder-style="color:#ccc" type="text" />
			</view>
		</view>
		<partTree :keyword="keyword" @onChecked="nodeClick" :tree="filteredData" :disabledIdArr="disabledIdArr"
			v-if="filteredData.length" :key="treeKey">
		</partTree>
		<view class="empty" v-else>
			<view class="circle">
				<image src="@/static/images/emptyS.png"></image>
			</view>
			<view class="title">
				暂无搜索结果
			</view>
		</view>
		<view class="bottom-block">

		</view>
		<view class="item_botm" @click="imTasksClick">
			<view :class="['botm']">{{ isFlag ? '选择层站' : '确定' }}</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<view class="flag">
				<view class="line"><text></text></view>
				<view class="flagTitle">
					选择层站</view>
				<view class="flagContent">
					<partTree :tree="flagList" @onChecked="nodeClickFlag" :disabledIdArr="disabledIdArr" :isFlag="true">
					</partTree>
					<view class="empty"></view>
				</view>
				<view class="item_botm" @click="imTasksClickFlag">
					<view :class="['botm']">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import partTree from '@/components/select-tree/select-tree.vue';
import { getTree, getTreeNew, getTemplateTree, getTemplateTreeList } from '@/apis/elevator.js';
import { debounce, memoize, createPerformanceMonitor } from '@/utils/performance.js';

export default {
	components: { partTree },
	data() {
		return {
			focusState: false,
			keyword: '',
			keywords: '',
			tree: [],
			data: [],
			// 勾选的数据 
			checkArr: [],
			form: {},
			selectId: '',
			ids: [],
			names: [],
			showOther: false,
			other: '',
			disabledIdArr: [],
			elevatorId: '',
			flagList: [],
			isFlag: false,
			// 当前选中节点
			checkedItem: null,
			// 来源页面
			formPage: '',
			// 优化相关
			treeKey: 0, // 用于强制更新树组件
			searchCache: new Map(), // 搜索缓存
			isLoading: false, // 加载状态
			processedTree: null, // 处理后的树数据
			performanceMonitor: createPerformanceMonitor(), // 性能监控
		};
	},
	computed: {
		// 计算过滤后的数据，避免频繁重新渲染
		filteredData() {
			if (!this.keyword) {
				return this.data;
			}

			// 使用memoize优化过滤函数
			const memoizedFilter = memoize((tree, keyword) => {
				return this.filterTree(JSON.parse(JSON.stringify(tree)), keyword);
			});

			return memoizedFilter(this.tree, this.keyword);
		}
	},
	onLoad(os) {
		if (os.formPage) {
			this.formPage = os.formPage;
		}
		if (os.elevatorId) {
			this.elevatorId = os.elevatorId;
		}
		if (os.disabledArr && os.disabledArr !== 'undefined') {
			this.disabledIdArr = [];
			let arr = JSON.parse(os.disabledArr);
			arr.forEach(item => {
				if (item.partsIds.length == item.partsNames.length) {
					if (item.floorStandIds) {
						// 禁止重复id 数组 当前判断是 区分层站
						this.disabledIdArr.push({
							partsId: item.partsIds[item.partsIds.length - 1],
							floorStandId: item.floorStandIds.split(',')[item.floorStandIds.split(',').length - 1]
						});
					} else {
						this.disabledIdArr.push({ partsId: item.partsIds[item.partsIds.length - 1] });
					}
				}
			});
		}
		this.loadTreeData();
	},
	methods: {
		// 优化数据加载
		async loadTreeData() {
			if (this.isLoading) return;

			const perfOp = this.performanceMonitor.start('loadTreeData');
			this.isLoading = true;
			uni.showLoading({
				title: '加载中',
				mask: true
			});

			try {
				const res = await getTreeNew({ elevatorId: this.elevatorId });
				let arr = res.data || [];

				if (arr.length === 0) {
					const fallbackRes = await getTree();
					arr = fallbackRes.data || [];
				}

				// 预处理数据
				this.processTreeData(arr);

			} catch (error) {
				console.error('加载树数据失败:', error);
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
				uni.hideLoading();
				this.performanceMonitor.end(perfOp);
			}
		},

		// 预处理树数据，避免重复处理
		processTreeData(arr) {
			const processed = this.processTreeNodes(arr);
			this.tree = processed;
			this.data = JSON.parse(JSON.stringify(this.tree));
			this.treeKey++; // 强制更新组件
		},

		// 处理树节点数据
		processTreeNodes(list) {
			return list.map(item => {
				const processed = {
					...item,
					type: this.formPage === 'applyParts' ? (item.structureType === 1 ? 1 : 2) : 2
				};

				if (processed.children && processed.children.length) {
					// 只处理第一层
					if (processed.parentId == 0) {
						processed.children.push({
							id: processed.id + '-other',
							name: '其他',
							parentId: processed.id,
							type: 2
						});
					}
					processed.children = this.processTreeNodes(processed.children);
				}

				return processed;
			});
		},
		// 清空搜索
		searchClear() {
			this.keywords = '';
			this.keyword = '';
			this.data = JSON.parse(JSON.stringify(this.tree));
			this.$nextTick(() => {
				this.focusState = true;
			});
		},

		// 搜索
		searchFuc(val) {
			this.keyword = this.keywords;
			if (!this.keyword) {
				this.data = JSON.parse(JSON.stringify(this.tree));
			}
			// 过滤逻辑移到computed中处理
		},

		// 点击每一项（选中或取消选中）
		nodeClick(res) {
			console.log(res);
			this.checkedItem = res;
			this.selectId = res.id || '';
			let partsId = res.id;
			this.names = res.names || [];

			// 异步加载层站数据
			this.loadFloorData(res);

			let ids = res.ids;
			if (this.selectId.indexOf('other') != -1) {
				if (ids.length && ids[ids.length - 1].indexOf('other') != -1) {
					ids.splice(ids.length - 1, 1);
				}
				this.ids = ids || [];
				this.showOther = true;
			} else {
				this.ids = ids || [];
				this.other = '';
				this.showOther = false;
			}
		},

		// 异步加载层站数据
		async loadFloorData(res) {
			try {
				if (res.flag == 2) {
					const floorRes = await getTemplateTree({
						elevatorId: this.elevatorId,
						flag: res.flag,
						partsId: res.id
					});

					this.flagList = floorRes.data.map(item => {
						item.partsId = res.id;
						item.name = item.name + '层';
						item.type = 2;
						if (item.children && item.children.length) {
							item.children.forEach(it => {
								it.partsId = res.id;
								it.type = 2;
							});
						}
						return item;
					});

				} else if (res.flag == 1) {
					const floorRes = await getTemplateTreeList({
						elevatorId: this.elevatorId,
						flag: res.flag,
						partsId: res.id
					});

					floorRes.data.forEach(item => {
						if (item.flag == 1) {
							item.type = 2;
							item.name = item.name + '层';
						}
					});
					this.flagList = floorRes.data.filter(item => item.flag == 1);
				} else {
					this.flagList = [];
				}

				this.isFlag = this.flagList.length > 0;

			} catch (error) {
				console.error('加载层站数据失败:', error);
				this.flagList = [];
				this.isFlag = false;
			}
		},

		// 点击层站任一级
		nodeClickFlag(res) {
			this.flag = res;
		},

		// 确定
		imTasksClick() {
			if (this.isFlag) {
				this.$refs.popup.open();
				return;
			}
			if (this.showOther && this.other.length == 0) {
				uni.showToast({
					title: '自定义配件名称不能为空',
					icon: 'none'
				});
				return;
			}
			if (this.showOther && this.names.length) {
				this.names[this.names.length - 1] = '其他-' + this.other;
			}
			if (this.showOther && this.other.length) {
				// 同步 
			}
			// 为空的时候错误提示，不允许点击确定
			if (!this.selectId && !this.other) {
				uni.showToast({
					title: '请选择配件！',
					icon: 'none'
				});
				return;
			}
			uni.$emit('part-selectd', { id: this.selectId, names: this.names, ids: this.ids, other: this.other, checkedItem: this.checkedItem });
			setTimeout(() => {
				uni.navigateBack();
			}, 300);
		},

		imTasksClickFlag() {
			if (!this.flag.id) {
				uni.showToast({
					title: '请选择层站！',
					icon: 'none'
				});
				return;
			}
			uni.$emit('part-selectd', { id: this.selectId, names: this.names, ids: this.ids, other: this.other, flag: this.flag, checkedItem: { ...this.checkedItem, skuIds: this.flag.skuIds, skuInfos: this.flag.skuInfos } });
			setTimeout(() => {
				uni.navigateBack();
			}, 300);
		},

		// 优化关键词过滤
		filterTree(nodes, query) {
			if (!(nodes && nodes.length)) {
				return [];
			}

			const predicate = (node) => node.name.includes(query);
			const newChildren = [];

			for (let node of nodes) {
				// 避免重复设置type
				if (!node.hasOwnProperty('type')) {
					if (this.formPage === 'applyParts') {
						node.type = (node.structureType === 1 ? 1 : 2);
					} else {
						node.type = 2;
					}
				}

				if (node.children && node.children.length) {
					node.show = true;
				}

				const subs = this.filterTree(node.children, query);

				if (predicate(node)) {
					newChildren.push({ ...node, id: node.id, name: node.name, parentId: node.parentId, show: node.show, type: node.type, children: subs });
				} else if (subs && subs.length) {
					node.children = subs;
					newChildren.push(node);
				}
			}
			return newChildren;
		}
	}
};
</script>

<style lang="scss" scoped>
page {
	background-color: #f6f6f6;
	color: #333;
	width: 100%;
}

.empty {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 300rpx;

	.circle {
		width: 64rpx;
		height: 64rpx;
	}

	image {
		width: 64rpx;
		height: 64rpx;
	}

	.title {
		font-size: 26rpx;
		color: #999;
		font-weight: 400;
		margin-top: 10rpx;
	}
}

.wrap {
	background-color: #f6f6f6;
	width: 100%;
	min-height: 100vh;

	.item_botm {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 99;
		background-color: #ffffff;
		padding: 0 20rpx 0rpx 20rpx;
		height: 98rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border-top: 1rpx #eee solid;

		/* #ifdef H5 */
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		/* #endif */

		.botm {
			width: 720rpx;
			margin: 0 auto;
			height: 70rpx;
			background: #0091ff;
			border-radius: 8rpx;
			line-height: 70rpx;
			text-align: center;
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
		}

		.botmbg {
			background: #efefef;
			color: #cccccc;
		}
	}
}

.bottom-block {
	width: 100%;
	height: 240rpx;
}

.search-bar {
	background-color: #fff;
	width: 100%;
	margin-bottom: 16rpx;
	display: flex;
	flex-wrap: wrap;
	position: sticky;
	top: 0;
	z-index: 99;

	.line {
		width: 100%;
		height: 1px;
		background-color: #e9e9e9;
	}

	.search-bar-inp {
		width: 710rpx;
		margin: 24rpx auto;
		background-color: #f6f6f6;
		border-radius: 8rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.marginR {
			margin-right: 20rpx;
		}

		input {
			font-size: 26rpx;
			flex: 1;
			padding: 12rpx 28rpx;
		}

		.btn {
			width: 90rpx;
			text-align: center;
			height: auto;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
}

.flag {
	background: #ffffff;
	border-radius: 8rpx;
	box-sizing: border-box;
	box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.2);
	max-height: 80vh;
	padding-top: 20rpx;

	.flagTitle {
		color: #333;
		font-weight: 500;
		font-size: 32rpx;
		padding-left: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #eee;
	}

	.flagContent {
		background: #f6f6f6;

		.empty {
			height: 100rpx;
		}
	}

	.line {
		display: flex;
		justify-content: center;

		text {
			width: 64rpx;
			height: 10rpx;
			background: #d8d8d8;
			border-radius: 6rpx;
		}
	}
}
</style>
